/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
    if (arguments.length === 0) {
        return null;
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
    let date;
    if (typeof time === 'object') {
        date = time;
    } else {
        if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
            time = parseInt(time);
        }
        if (typeof time === 'number' && time.toString().length === 10) {
            time = time * 1000;
        }
        date = new Date(time);
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    };
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value];
        }
        if (result.length > 0 && value < 10) {
            value = '0' + value;
        }
        return value || 0;
    });
    return time_str;
}

/**
 * Parse the time to chinese
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTimeToCh(time, cFormat) {
    if (arguments.length === 0) {
        return null;
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
    let date;
    if (typeof time === 'object') {
        date = time;
    } else {
        if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
            time = parseInt(time);
        }
        if (typeof time === 'number' && time.toString().length === 10) {
            time = time * 1000;
        }
        date = new Date(time);
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    };

    return `${formatObj.y}年${formatObj.m}月${formatObj.d}日`;
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
    let date = new Date(time);
    let year = date.getFullYear();
    let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
    let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    let hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    let minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    let second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    let currentTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    return currentTime;
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
    const search = url.split('?')[1];
    if (!search) {
        return {};
    }
    return JSON.parse(
        '{"' +
            decodeURIComponent(search)
                .replace(/"/g, '\\"')
                .replace(/&/g, '","')
                .replace(/=/g, '":"')
                .replace(/\+/g, ' ') +
            '"}'
    );
}
//获取省信息
export function initProvince() {
    let data = JSON.parse(localStorage.getItem('province'));
    var provinceList = [];
    for (var i = 0; i < data.length; i++) {
        var keys = Object.keys(data[i]);
        keys.forEach(value => {
            provinceList.push({ value: value, label: data[i][value].n });
        });
    }
    return provinceList;
}
//获取省下面对应的市
export function initCity(pid) {
    if (pid !== '' && pid !== null && pid !== undefined && !isNaN(pid)) {
        let data = JSON.parse(localStorage.getItem('province'));
        var provIndex = -1;
        var provinceList = [];
        for (var i = 0; i < data.length; i++) {
            var keys = Object.keys(data[i]);
            keys.forEach(value => {
                provinceList.push({ value: value.toString(), label: data[i][value].n });
            });
        }
        provinceList.forEach((item, index) => {
            if (item.value === pid) {
                provIndex = index;
            }
        });
        if (provIndex !== -1) {
            let item = data[provIndex][pid];
            var cityArray = [];
            Object.keys(item).forEach((city, index) => {
                if (city !== 'n') {
                    cityArray.push({ value: city, label: item[city].n });
                }
            });
            return cityArray;
        }
    } else {
        return [];
    }
}
//初始化区
export function initRegion(provinceId, pid) {
    if (pid !== '' && pid !== null && pid !== undefined && !isNaN(pid)) {
        let data = JSON.parse(localStorage.getItem('province'));
        var provIndex = -1;
        var provinceList = [];
        for (var i = 0; i < data.length; i++) {
            var keys = Object.keys(data[i]);
            keys.forEach(value => {
                provinceList.push({ value: value, label: data[i][value].n });
            });
        }
        provinceList.forEach((item, index) => {
            if (item.value === provinceId) {
                provIndex = index;
            }
        });
        var cityData = data[provIndex][provinceId];
        let item = cityData[pid];
        var regionArray = [];
        Object.keys(item).forEach((region, index) => {
            if (region !== 'n') {
                regionArray.push({ value: region, label: item[region].n });
            }
        });
        return regionArray;
    } else {
        return [];
    }
}

export const pickerOptions = {
    disabledDate: function(dateA) {
        dateA.setHours(0, 0, 0, 0);
        let dateB = new Date();
        dateB.setHours(0, 0, 0, 0);

        return dateA.getTime() >= dateB.getTime();
    },
    shortcuts: [
        {
            text: '本周',
            onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setDate(start.getDate() - start.getDay() + 1);
                start.setHours(0);
                start.setMinutes(0);
                start.setSeconds(0);
                start.setMilliseconds(0);
                picker.$emit('pick', [start, end]);
            }
        },
        {
            text: '上周',
            onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setDate(start.getDate() - start.getDay() + 1 - 7);
                start.setHours(0);
                start.setMinutes(0);
                start.setSeconds(0);
                start.setMilliseconds(0);
                end.setDate(end.getDate() - end.getDay() + 1);
                end.setHours(0);
                end.setMinutes(0);
                end.setSeconds(0);
                end.setMilliseconds(0);
                picker.$emit('pick', [start, end]);
            }
        },
        {
            text: '本月',
            onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setDate(1);
                start.setHours(0);
                start.setMinutes(0);
                start.setSeconds(0);
                start.setMilliseconds(0);
                picker.$emit('pick', [start, end]);
            }
        },
        {
            text: '上个月',
            onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setMonth(start.getMonth() - 1);
                start.setDate(1);
                start.setHours(0);
                start.setMinutes(0);
                start.setSeconds(0);
                start.setMilliseconds(0);
                end.setDate(1);
                end.setHours(0);
                end.setMinutes(0);
                end.setSeconds(0);
                end.setMilliseconds(0);
                picker.$emit('pick', [start, end]);
            }
        }
    ]
};

export function alertSuccess(msg, obj) {
    obj.$notify({
        title: '成功',
        message: msg,
        type: 'success'
    });
}
export function alertError(msg, obj) {
    console.log(msg);
    obj.$notify({
        title: '失败',
        message: msg,
        type: 'error'
    });
}
export function alertWarning(msg, obj) {
    obj.$notify({
        title: '提醒',
        message: msg,
        type: 'warning'
    });
}

export function formatDateToString(date) {
    if (date instanceof Date) {
        let yyyy = date.getFullYear();
        let MM = (date.getMonth() + 1 + '').padStart(2, '0');
        let DD = (date.getDate() + '').padStart(2, '0');
        let HH = (date.getHours() + '').padStart(2, '0');
        let mm = (date.getMinutes() + '').padStart(2, '0');
        let ss = (date.getSeconds() + '').padStart(2, '0');
        return `${yyyy}-${MM}-${DD}`;
    } else {
        return undefined;
    }
}

export function formatDateToString2(date) {
    if (date instanceof Date) {
        let yyyy = date.getFullYear();
        let MM = (date.getMonth() + 1 + '').padStart(2, '0');
        let DD = (date.getDate() + '').padStart(2, '0');
        let HH = (date.getHours() + '').padStart(2, '0');
        let mm = (date.getMinutes() + '').padStart(2, '0');
        let ss = (date.getSeconds() + '').padStart(2, '0');
        return `${yyyy}-${MM}-${DD} ${HH}:${mm}:${ss}`;
    } else {
        return undefined;
    }
}
